﻿<?php
	//require_once('./sys/sys.php');

	class photo{
		private $photo_name;
		private $tmp_name;
		private $photo_path;
		private $photo_type;
		private $photo_exif = '';
		private $real_path;
		private $pic_size;
		private $pic_id;
		private $sort_id,$job_id,$album_id,$cache_id;
		private $pic_tb_x = 75;
		private $pic_tb_y = 75;
		private $font_file;
		private $is_jpeg = false;
		private $is_png = false;
		private $can_save = false;
		private $db_settings = array();
		private $cache_file = '';
		
		function __construct($db_settings,$photo_name,$photo_type,$photo_path,$font_file,$pic_tb_x,$pic_tb_y){
			$this->pic_tb_x = $pic_tb_x;
			$this->pic_tb_y = $pic_tb_y;
			$this->photo_type = $photo_type;
			if (!is_array($db_settings)) {
				$this->db_settings = init_db_settings();
			}else 
				$this->db_settings = $db_settings;
			$this->photo_name = $photo_name;
			if (!is_file($photo_path)) {
				$this->pic_error('None of this file',-2);
			}
			$this->photo_path = $photo_path;
			$this->real_path = $photo_path;
			if (!is_file($font_file)) {
				$this->font_file = $font_file;
			}
		}
		/**
		 * 删除上传文件;
		 *
		 */
		function __destruct(){
			if (is_file($this->photo_path)) {
				@$this->destroy_file($this->photo_path);
			}
		}
		/**
		 * 从文件中创建一个图象资源
		 *
		 * @return  image_source
		 */
		private function get_image_source(){
			if (!is_file($this->real_path)) {
				$this->pic_error('None of this file',-1);
			}
			$file_path = $this->real_path;
			switch ($this->photo_type) {
				case 'image/pjpeg':
						$test_img = imagecreatefromjpeg($file_path);
						$this->can_save = true;
						$this->is_jpeg = true;
					break;
				case 'image/jpeg':
						$test_img = imagecreatefromjpeg($file_path);
						$this->can_save = true;
						$this->is_jpeg = true;
					break;
				case 'image/gif':
						$test_img = imagecreatefromgif($file_path);
						$this->can_save = true;
					break;
				case 'image/x-png':
						$test_img = imagecreatefrompng($file_path);
						$this->is_png = true;
						$this->can_save = true;
					break;
				default:
						
						$test_img = imagecreate(1024,768);
						$skyblue = ImageColorAllocate($test_img,136,193,255);
						ImageFill($test_img,0,0,$skyblue);
						$white = ImageColorAllocate($test_img, 255,255,255);
						//将GB字符转换成UTF8字符
						$str = chr(0xE6) . chr(0xB2) . chr(0xA1) . chr(0xE6) . chr(0x9C) . chr(0x89) . chr(0xE8) . chr(0xAF) . chr(0xA5) . chr(0xE5) . chr(0x9B) . chr(0xBE) . chr(0xE7) . chr(0x89) . chr(0x87);
						$str .= chr(0xE6) . chr(0x88) . chr(0x96) . chr(0xE8) . chr(0xAF) . chr(0xA5) . chr(0xE5) . chr(0x9B) . chr(0xBE) . chr(0xE7) . chr(0x89) . chr(0x87) . chr(0xE6) . chr(0xA0) . chr(0xBC) . chr(0xE5) . chr(0xBC) . chr(0x8F) . chr(0xE4) . chr(0xB8) . chr(0x8D) . chr(0xE6) . chr(0xAD) . chr(0xA3) . chr(0xE7) . chr(0xA1) . chr(0xAE);					
						if (!is_file($font_file)) {
							imagestring($test_img,4,120,300,'Unknow pic type',$white);
						}
						else 
							imagettftext($test_img,40,0,120,380,$white,$font_file,$str);
					break;
			}
			return $test_img;
		}
		/**
		 * 出错处理
		 *
		 * @param string $err_msg
		 * @param integer $return_value
		 * @return integer
		 */
		private function pic_error($err_msg,$return_value){
			if ($err_msg != '') {
				$mes = $error_msg;
			}
			else 
				$mes = 'Unknown error<br>';
				
			//file_put_contents('1.txt',$mes);
			
			echo $mes;
			if (!is_numeric($return_value)) {
				return false;
			}
			else 
				return $return_value;
		}
		/**
		 * 删除文件用
		 *
		 * @param string $file_path
		 */
		public  function destroy_file($file_path){
			if (is_file($file_path) && is_writeable($file_path)) {
				$result = unlink($file_path);
				return $result;
			}
			else 
				return false;
		}
		
		private function GetImageInfoVal($ImageInfo,$val_arr) {  
			$InfoVal = "未知";  
				foreach($val_arr as $name=>$val) {  
					if ($name==$ImageInfo) {  
						$InfoVal = &$val;  
						break;  
					}  
				}  
			return $InfoVal;  
		}  
		/**
		 * 将图片存储到数据库中
		 *
		 * @param string $file_path
		 * @param array $db_settings
		 * @return integer
		 */
		private function save_pic_to_database($file_path,$db_settings,$sort_id,$job_id,$album_id,$cache_id,$photo_title = '默认标题',$photo_des = '默认描述',$use_jpeg = false){
			
			if (is_file($file_path)) {
				$fsize = filesize($file_path);
				$fstring = addslashes(fread(fopen($file_path,"r"),$fsize));
				$thumb_string = $this->create_thunmbs($file_path,$use_jpeg);
				if (!$thumb_string) {
					$this->pic_error('Can not create thumb of this picture!',-1);
				}
				$exif_str = $this->photo_exif;
				if (!$this->photo_exif) {
					$exif_str = '';
				}
				$photo_title = substr((ADD_addslashes($photo_title)),0,100);
				$photo_des = substr((ADD_addslashes($photo_des)) , 0 ,198);
				$current_time = time();
				$p_sid = $current_time + mt_rand(100,999);
				$this->pic_id = $p_sid;
				$sql = array();
				$sql[] = "INSERT INTO {$db_settings['tb_pre']}photos VALUES($p_sid,'$fstring')";
				$sql[] = "INSERT INTO {$db_settings['tb_pre']}photothumbs VALUES('$p_sid','$sort_id','$job_id','$album_id','0','$photo_title','$photo_des','$thumb_string','$exif_str','$current_time',0)";
				//初始化数据库对象
				$photo_sql = new photo_mysql($db_settings['host'],$db_settings['user'],$db_settings['pass'],$db_settings['dbname'],$db_settings['tb_pre']);	
				$photo_sql->insert($sql);
				
				return $p_sid;
			}
			else 
				return false;
		}
		/** 
		* 获取图象信息的函数  
		*  
		* 一个全面获取图象信息的函数  
		*  
		* @access public  
		* @param string $img 图片路径  
		* @return array  
		*/
		public function GetImageInfo($img) {
			$imgtype = array(
				"", "GIF", "JPG", "PNG", "SWF", "PSD", "BMP", "TIFF(intel byte order)", "TIFF(motorola byte order)", "JPC", "JP2", "JPX", "JB2", "SWC", "IFF", "WBMP", "XBM"
			);  
			$Orientation = array(
				"", "top left side", "top right side", "bottom right side", "bottom left side", "left side top", "right side top", "right side bottom", "left side bottom"
			);  
			$ResolutionUnit = array(
				"", "", "英寸", "厘米"
			);  
			$YCbCrPositioning = array(
				"", "the center of pixel array", "the datum point"
			);  
			$ExposureProgram = array(
				"未定义", "手动", "标准程序", "光圈先决", "快门先决", "景深先决", "运动模式", "肖像模式", "风景模式"
			);  
			$MeteringMode_arr = array(  
				"0" => "未知",  
				"1" => "平均",  
				"2" => "中央重点平均测光",  
				"3" => "点测",  
				"4" => "分区",  
				"5" => "评估",  
				"6" => "局部",  
				"255" => "其他"  
			);  
			$Lightsource_arr = array(  
				"0" => "未知",  
				"1" => "日光",  
				"2" => "荧光灯",  
				"3" => "钨丝灯",  
				"10" => "闪光灯",  
				"17" => "标准灯光A",  
				"18" => "标准灯光B",  
				"19" => "标准灯光C",  
				"20" => "D55",  
				"21" => "D65",  
				"22" => "D75",  
				"255" => "其他"  
			);  
			$Flash_arr = array(  
				"0" => "无闪光",  
				"1" => "有闪光",  
				"5" => "有闪光但虑光镜没反应",  
				"7" => "有闪光且虑光镜有反应",  
			);
			$exif = exif_read_data ($img,"IFD0");  
			if ($exif===false) {  
				$new_img_info = array ("文件信息" => "没有图片EXIF信息");  
			}  
			else  
			{  
				$exif = exif_read_data ($img,0,true);  
				$new_img_info = array (  
					"文件信息" => "-----------------------------",  
					"文件名" => $exif[FILE][FileName],  
					"文件类型" => $imgtype[$exif[FILE][FileType]],  
					"文件格式" => $exif[FILE][MimeType],  
					"文件大小" => $exif[FILE][FileSize],  
					"时间戳" => date("Y-m-d H:i:s",$exif[FILE][FileDateTime]),  
					"图像信息" => "-----------------------------",  
					"图片说明" => $exif[IFD0][ImageDescription],  
					"制造商" => $exif[IFD0][Make],  
					"型号" => $exif[IFD0][Model],  
					"方向" => $Orientation[$exif[IFD0][Orientation]],  
					"水平分辨率" => $exif[IFD0][XResolution].$ResolutionUnit[$exif[IFD0][ResolutionUnit]],  
					"垂直分辨率" => $exif[IFD0][YResolution].$ResolutionUnit[$exif[IFD0][ResolutionUnit]],  
					"创建软件" => $exif[IFD0][Software],  
					"修改时间" => $exif[IFD0][DateTime],  
					"作者" => $exif[IFD0][Artist],  
					"YCbCr位置控制" => $YCbCrPositioning[$exif[IFD0][YCbCrPositioning]],  
					"版权" => $exif[IFD0][Copyright],  
					"摄影版权" => $exif[COMPUTED][Copyright.Photographer],  
					"编辑版权" => $exif[COMPUTED][Copyright.Editor],  
					"拍摄信息" => "-----------------------------",  
					"Exif版本" => $exif[EXIF][ExifVersion],  
					"FlashPix版本" => "Ver. ".number_format($exif[EXIF][FlashPixVersion]/100,2),  
					"拍摄时间" => $exif[EXIF][DateTimeOriginal],  
					"数字化时间" => $exif[EXIF][DateTimeDigitized],  
					"拍摄分辨率高" => $exif[COMPUTED][Height],  
					"拍摄分辨率宽" => $exif[COMPUTED][Width],  
					/*  
					The actual aperture value of lens when the image was taken.  
					Unit is APEX.  
					To convert this value to ordinary F-number(F-stop),  
					calculate this value's power of root 2 (=1.4142).  
					For example, if the ApertureValue is '5', F-number is pow(1.41425,5) = F5.6.  
					*/  
					"光圈" => $exif[EXIF][ApertureValue],  
					"快门速度" => $exif[EXIF][ShutterSpeedValue],  
					"快门光圈" => $exif[COMPUTED][ApertureFNumber],  
					"最大光圈值" => "F".$exif[EXIF][MaxApertureValue],  
					"曝光时间" => $exif[EXIF][ExposureTime],  
					"F-Number" => $exif[EXIF][FNumber],  
					"测光模式" => $this->GetImageInfoVal($exif[EXIF][MeteringMode],$MeteringMode_arr),  
					"光源" => $this->GetImageInfoVal($exif[EXIF][LightSource], $Lightsource_arr),  
					"闪光灯" => $this->GetImageInfoVal($exif[EXIF][Flash], $Flash_arr),  
					"曝光模式" => ($exif[EXIF][ExposureMode]==1?"手动":"自动"),  
					"白平衡" => ($exif[EXIF][WhiteBalance]==1?"手动":"自动"),  
					"曝光程序" => $ExposureProgram[$exif[EXIF][ExposureProgram]],  
					/*  
					Brightness of taken subject, unit is APEX. To calculate Exposure(Ev) from BrigtnessValue(Bv), you must add SensitivityValue(Sv).  
					Ev=Bv+Sv Sv=log((ISOSpeedRating/3.125),2)  
					ISO100:Sv=5, ISO200:Sv=6, ISO400:Sv=7, ISO125:Sv=5.32.  
					*/  
					"曝光补偿" => $exif[EXIF][ExposureBiasValue]."EV",  
					"ISO感光度" => $exif[EXIF][ISOSpeedRatings],  
					"分量配置" => (bin2hex($exif[EXIF][ComponentsConfiguration])=="01020300"?"YCbCr":"RGB"),//'0x04,0x05,0x06,0x00'="RGB" '0x01,0x02,0x03,0x00'="YCbCr"  
					"图像压缩率" => $exif[EXIF][CompressedBitsPerPixel]."Bits/Pixel",  
					"对焦距离" => $exif[COMPUTED][FocusDistance]."m",  
					"焦距" => $exif[EXIF][FocalLength]."mm",  
					"等价35mm焦距" => $exif[EXIF][FocalLengthIn35mmFilm]."mm",  
					/*  
					Stores user comment. This tag allows to use two-byte character code or unicode. First 8 bytes describe the character code. 'JIS' is a Japanese character code (known as Kanji).  
					'0x41,0x53,0x43,0x49,0x49,0x00,0x00,0x00':ASCII  
					'0x4a,0x49,0x53,0x00,0x00,0x00,0x00,0x00':JIS  
					'0x55,0x4e,0x49,0x43,0x4f,0x44,0x45,0x00':Unicode  
					'0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00':Undefined  
					*/  
					"用户注释编码" => $exif[COMPUTED][UserCommentEncoding],  
					"用户注释" => $exif[COMPUTED][UserComment],  
					"色彩空间" => ($exif[EXIF][ColorSpace]==1?"sRGB":"Uncalibrated"),  
					"Exif图像宽度" => $exif[EXIF][ExifImageLength],  
					"Exif图像高度" => $exif[EXIF][ExifImageWidth],  
					"文件来源" => (bin2hex($exif[EXIF][FileSource])==0x03?"digital still camera":"unknown"),  
					"场景类型" => (bin2hex($exif[EXIF][SceneType])==0x01?"A directly photographed image":"unknown"),  
					"缩略图文件格式" => $exif[COMPUTED][Thumbnail.FileType],  
					"缩略图Mime格式" => $exif[COMPUTED][Thumbnail.MimeType]  
				);  
			}  
			return $new_img_info;  
		}  
		/**
		 * 从数据库中取出图片进行显示
		 *
		 * @param int $pid
		 * @param bool $only_thumb
		 */
		public function show_pic_from_database($pid,$only_thumb = true){
			header("Content-type: image/png");
			$db_settings = $this->db_settings;
			$photo_char = 'photo';
			if (!$only_thumb) {
				$sql = "SELECT `photo` FROM " . $db_settings['tb_pre'] . "photos WHERE photo_id=$pid";
				$photo_char = 'photo';
			}
			else {
				$sql = "SELECT `photothumbs` FROM " . $db_settings['tb_pre'] . "photothumbs WHERE photothumbs_id=$pid";
				$photo_char = 'photothumbs';
			}
			$photo_sql = new photo_mysql($db_settings['host'],$db_settings['user'],$db_settings['pass'],$db_settings['dbname'],$db_settings['tb_pre']);
			$result = $photo_sql->get_one($sql);
			$image = $result->$photo_char;
			echo $image;
			return 0;
		}
		/**
		 * 缓存上传文件
		 *
		 * @param string $tmp_file
		 * @param int $album_id
		 * @param string $file_type
		 * @param int $pic_x
		 * @param int $pic_y
		 * 
		 * @return string $file_name
		 */
		private function pic_hashed($tmp_file,$album_id,$file_type = 'jpg',$pic_x = 80,$pic_y = 80){
				//获取缓存文件夹名
				$dir_name = pic_hash_dir('upload');
				$file_name = time() . mt_rand(100,999) . '.' .$file_type;
				//如果该文件夹不存在
				if (!is_dir($dir_name[1] )) {
					mkdir($dir_name[1],7777);
				}
				$cache_file = $dir_name[1] . $file_name;
				//保存缓存文件
				@copy($tmp_file,$cache_file);
				//生成缩略图
				resize_pic_for_slidshow($pic_x,$pic_y,$cache_file);
				//将缓存信息保存到数据库中
				$hash_id = time() . mt_rand(0,999);
				global $DB;
				$DB->do_insert( 'hash_cache' , array( 'cache_id'	=> $hash_id,
					'cache_folder'			=> $cache_file,
					'uid'					=> $album_id,
					'date'					=> get_date(time()),
					'result'				=> 1
				));
				
				
				
				
				//更新图片表的cache ID
				$DB->do_update( 'photothumbs', array( 'cache_id' => $hash_id ),'photothumbs_id=' . $this->pic_id);
				$this->cache_id = $hash_id;
				$this->cache_file = $cache_file;
				return $cache_file;
		}
		/**
		 * 保存图片文件
		 *
		 * @param unknown_type $db_settings
		 * @param unknown_type $sort_id
		 * @param unknown_type $job_id
		 * @param unknown_type $album_id
		 * @param unknown_type $cache_id
		 * @return unknown
		 */
		public function save_pic($db_settings,$sort_id,$job_id,$album_id,$cache_id,$photo_title = '默认标题',$photo_des = '默认描述',$save_in_jpeg = false,$with_cached = true){
			if (!is_numeric($sort_id) || !is_numeric($job_id) || !is_numeric($album_id) || !is_numeric($cache_id)) {
				$this->pic_error('ERROR job id<br>',false);
			}
			
			$this->sort_id = $sort_id;
			$this->job_id = $job_id;
			$this->album_id = $album_id;
			$this->cache_id = $cache_id;
			$img_source = $this->get_image_source();
			//如果不允许存储,直接显示非法图片
			if (!$this->can_save) {
				//$this->show_pic($img_source);
				return -3;
			}
			//获取图片的exif
			if ($this->photo_type == 'image/pjpeg') {
				$exif_array = $this->GetImageInfo($this->photo_path);
				//串行化EXIF关联数组
				$this->photo_exif = substr(addslashes(serialize($exif_array)),0,65534);
			}
			else 
				$exif_array = '';
			//获取临时文件的路径
			$file_dir = dirname($this->photo_path);
			$last_char = substr($file_dir,(strlen($file_dir) - 1));
			if ($last_char != '/' || $last_char != "\\") {
				$file_dir .= '/';
			}
			
			//保存为PNG图象
			if (!$save_in_jpeg) {
				//非PNG图象的转换为PNG图象
				if (!$this->is_png) {
					$tmp_file = $file_dir . time() . '.png';
					$result = imagepng($img_source,$tmp_file);
					if ($result) {
						$this->destroy_file($this->photo_path);
						imagedestroy($img_source);
						//将图象,以及EXIF信息保存到数据库
						$result = $this->save_pic_to_database($tmp_file,$db_settings,$sort_id,$job_id,$album_id,$cache_id,$photo_title,$photo_des,$save_in_jpeg);
						if (!$result) {
							$this->destroy_file($tmp_file);
							$this->pic_error('can not save pic!',false);
						}
						//如果需要缓存
						if ($with_cached) {
							$this->pic_hashed($tmp_file,$album_id,'png',80,80);
						}
						//删除源文件
						$this->destroy_file($tmp_file);
					}
					else
						$this->pic_error('can not create tmp file',false);
				}
				else {
					$tmp_file = $this->photo_path;
					$result = $this->save_pic_to_database($tmp_file,$db_settings,$sort_id,$job_id,$album_id,$cache_id,$photo_title,$photo_des,$save_in_jpeg);
					if (!$result) {
						$this->destroy_file($tmp_file);
						$this->pic_error('can not save pic!',false);
					}
					//如果需要缓存
					if ($with_cached) {
						$this->pic_hashed($tmp_file,$album_id,'png',80,80);
					}
					//删除源文件
					$this->destroy_file($tmp_file);
				}
			}
			//保存为jpeg图象
			else {
				if (!$this->is_jpeg) {
					$tmp_file = $file_dir . time() . '.jpg';
					$result = imagejpeg($img_source,$tmp_file);
					if ($result) {
						$this->destroy_file($this->photo_path);
						imagedestroy($img_source);
						//将图象,以及EXIF信息保存到数据库
						$result = $this->save_pic_to_database($tmp_file,$db_settings,$sort_id,$job_id,$album_id,$cache_id,$photo_title,$photo_des,$save_in_jpeg);
						if (!$result) {
							$this->destroy_file($tmp_file);
							$this->pic_error('can not save pic!',false);
						}
						//如果需要缓存
						if ($with_cached) {
							$this->pic_hashed($tmp_file,$album_id,'jpg',80,80);
						}
						$this->destroy_file($tmp_file);
						
					}
					else
						$this->pic_error('can not create tmp file',false);
				}
				else {
					$tmp_file = $this->photo_path;
					$result = $this->save_pic_to_database($tmp_file,$db_settings,$sort_id,$job_id,$album_id,$cache_id,$photo_title,$photo_des,$save_in_jpeg);
					if (!$result) {
						$this->destroy_file($tmp_file);
						$this->pic_error('can not save pic!',false);
					}
					
					//如果需要缓存
					if ($with_cached) {
						$this->pic_hashed($tmp_file,$album_id,'jpg',80,80);
					}
					$this->destroy_file($tmp_file);
				}
			}
			if ($with_cached) {
				return $this->cache_file;
			}
			else 
				return true;
		}
		/**
		 * 创建一个缩略图并且返回缩略图的字符串
		 *
		 * @param string $file_path
		 * @return mixed
		 */
		public function create_thunmbs($file_path,$use_jpeg = false){
			if (!$use_jpeg) {
				$img_src = imagecreatefrompng($file_path);
			}
			else 
				$img_src = imagecreatefromjpeg($file_path);
			$imgx = imagesx($img_src);
			$imgy = imagesy($img_src);
			//如果图象超过大小将自动调整
			$photo_tb_x = $this->pic_tb_x;
			$photo_tb_y = $this->pic_tb_y;
			if ($imgy > $this->pic_tb_y || $imgx > $this->pic_tb_x) {
				if ($imgy / ($this->pic_tb_y) > $imgx / ($this->pic_tb_x)) {
					$scale = ($this->pic_tb_y) / $imgy;
					$photo_tb_x = $imgx * $scale;
					$photo_tb_y = $this->pic_tb_y;
				}
				else{
					$scale = ($this->pic_tb_x) / $imgx;
					$photo_tb_y = $imgy * $scale;
					$photo_tb_x = $this->pic_tb_x;
				}
			}
			$tb_img = imagecreatetruecolor($photo_tb_x,$photo_tb_y);
			imagecopyresampled($tb_img,$img_src,0,0,0,0,$photo_tb_x,$photo_tb_y,$imgx,$imgy);
			$file_dir = dirname($file_path);
			$last_char = substr($file_dir,(strlen($file_dir) - 1));
			if ($last_char != '/' || $last_char != "\\") {
				$file_dir .= '/';
			}
			$tmp_file = $file_dir . time() . 'thb.png';
			$result = imagepng($tb_img,$tmp_file);
			imagedestroy($img_src);
			imagedestroy($tb_img);
			if ($result != 1) {
				$this->destroy_file($tmp_file);
				return false;
			}
			$thumb_size = filesize($tmp_file);
			$thumb_string = addslashes(fread(fopen($tmp_file,'r'),$thumb_size));
			$this->destroy_file($tmp_file);
			return $thumb_string;
		}
		
		protected  function resize_pic($image_source,$width,$height){
			
			return $image_source;
		}
		/**
		 * 从资源中显示图片
		 *
		 * @param image _source $image_source
		 * @param string $image_type
		 */
		public function show_pic($image_source,$image_type = 'image/png'){
			header("Content-type: $image_type");
			imagepng($image_source);
			imagedestroy($image_source);
		}
		/**
		 * 获取类别ID
		 *
		 * @return unknown
		 */
		public function get_sort_id(){
			return $this->sort_id;
		}
		/**
		 * 获取工作ID
		 *
		 * @return unknown
		 */
		public function get_job_id(){
			return $this->job_id;
		}
		/**
		 * 获取相册ID
		 *
		 * @return unknown
		 */
		public function get_album_id(){
			return $this->album_id;
		}
		/**
		 * 获取缓存ID
		 *
		 * @return unknown
		 */
		public function get_cache_id(){
			return $this->cache_id;
		}
		/**
		 * 获取图片ID
		 *
		 * @return int
		 */
		public function get_pid(){
			return $this->pic_id;
		}
		
		public function get_exif($pid){
			$db_settings = $this->db_settings;
			$sql = "SELECT `photo_exif` FROM " . $db_settings['tb_pre'] . "photothumbs WHERE photothumbs_id=$pid";
			$photo_sql = new photo_mysql($db_settings['host'],$db_settings['user'],$db_settings['pass'],$db_settings['dbname'],$db_settings['tb_pre']);
			$result = $photo_sql->fetch_objs($sql);
			if (count($result) > 0) {
				$exif_str = $result[0]->photo_exif;
			}
			$exif_array = unserialize($exif_str);
			return $exif_array;
		}
		
	}
	
	class photo_mysql{
		private  $host = '';
		private  $pass = '';
		private  $user = '';
		private  $dbname = '';
		private  $prefix_db = '';
		private  $db_linker;
		private  $query_id;
		private  $num_rows;
		private  $affected_rows;
		private  $insert_id;
		
		
		/**
		 * 构造方法,用于建立数据库连接以及选定数据库
		 *
		 * @param unknown_type $host
		 * @param unknown_type $user
		 * @param unknown_type $pass
		 * @param unknown_type $dbname
		 * @param unknown_type $prefix_db
		 * @return unknown
		 */
		function __construct($host,$user,$pass,$dbname,$prefix_db){
			
			$db = mysql_connect($host,$user,$pass);
			if (!$db) {
				echo mysql_error($db);
				return false;
			}
			$this->db_linker = $db;
			$this->host = $host;
			$this->user = $user;
			$this->pass = $pass;
			$this->prefix_db = $prefix_db;
			$result = mysql_select_db($dbname,$db);
			if (!$result) {
				$this->dbhalt('Error database name please select another database<br>The error message is:<br>' . mysql_error($db),-1);
			}
			$this->dbname = $dbname;
			return $db;
		}
		
		function __destruct(){
			$this->dbclose();
		}
		
		/**
		 * 系统出错处理
		 *
		 * @param unknown_type $error_msg
		 * @param unknown_type $return_num
		 * @return unknown
		 */
		private function dbhalt($error_msg,$return_num){
			if ($error_msg != '') {
				$mes = $error_msg;
			}
			else 
				$mes = 'Unknown error';
			echo $mes;
			if (!is_numeric($return_num)) {
				return false;
			}
			else 
				return $return_num;
		}
		/**
		 * 查询并返回查询资源
		 *
		 * @param strings $sqls
		 * @return resoces
		 */
		private  function query($sqls){
			$result = false;
			$has_error = false;
			if (is_array($sqls)) {
				$result = array();
				$count = count($sqls);
				for ($i = 0; $i < $count; $i++){
					//$result[$i] = $db->query($sqls[$i]);
					$result[$i] = $this->query_id = mysql_query($sqls[$i],$this->db_linker);
					if ($result[$i] == false) {
						echo '无法执行第' . ($i+1) . '句查询语句:<br>' . $sqls[$i] . '<br>数据库错误信息为:<br>' . mysql_error($this->db_linker);
						if (!$has_error) {
							$has_error = true;
							$result['error'] = true;
						}
					}
				}
			}
			else{
				$result = $this->query_id = mysql_query($sqls,$this->db_linker);
				if ($result == false) {
					echo '无法执行查询语句:<br>' . $sqls . '<br>数据库错误信息为:<br>' . mysql_error($this->db_linker);
				}
			}
			return $result;
		}
		
		/**
		 * 选择系统数据库
		 *
		 * @param unknown_type $dbname
		 * @return unknown
		 */
		public function selec_db($dbname){
			if (is_null($this->db_linker) && $this->db_linker) {
				$this->dbhalt('Unvalid link source!',-3);
			}
			if (!mysql_select_db($dbname,$this->db_linker)) {
				$this->dbhalt('Can not select this database!',-2);
			}
		}
		/**
		 * 从数据库中查询出一行
		 *
		 * @param string $sql
		 * @return object
		 */
		public function get_one($sql){
			 $query_id = $this->query($sql);
			 $return_obj = mysql_fetch_object($query_id);
			 $this->num_rows = mysql_num_rows($query_id);
			 $this->dbfree_result($query_id);
			 return $return_obj;
		}
		/**
		 * 清除查询结果
		 *
		 * @param object $result_id
		 */
		public function dbfree_result($result_id){
			@mysql_free_result($result_id);
		}
		/**
		 * 直接获取查询结果
		 *
		 * @param string $sqls
		 * @return unknown
		 */
		public function fetch_objs($sqls){
			$array_result = array();
			$result = $this->query($sqls);
			if (is_array($result)) {
				$count = count($result);
				for ($i = 0 ; $i < $count ; $i++){
					if (!$result[$i]) {
						$array_result[$i][0] = false;
					}
					else {
						$this->num_rows = mysql_num_rows($result[$i]);
						for ($j = 0; $j < $this->num_rows ; $j ++){
							$array_result[$i][$j] = mysql_fetch_object($result[$i]);
						}
						$this->dbfree_result($result[$i]);
					}
				}
			}
			else if ($result) {
				$this->num_rows = mysql_num_rows($result);
				for ($i = 0 ; $i < $this->num_rows ; $i++){
					$array_result[$i] = mysql_fetch_object($result);
				}
				$this->dbfree_result($result);
			}
			else 
				$array_result = false;
			return $array_result;
		}
		/**
		 * 直接获取查询结果(返回关联数组)
		 *
		 * @param string $sqls
		 * @return unknown
		 */
		public function fetch_assoc($sqls){
			$array_result = array();
			$result = $this->query($sqls);
			if (is_array($result)) {
				$count = count($result);
				for ($i = 0 ; $i < $count ; $i++){
					if (!$result[$i]) {
						$array_result[$i][0] = false;
					}
					else {
						$this->num_rows = mysql_num_rows($result[$i]);
						for ($j = 0; $j < $this->num_rows ; $j ++){
							$array_result[$i][$j] = mysql_fetch_assoc($result[$i]);
						}
						$this->dbfree_result($result[$i]);
					}
				}
			}
			else if ($result) {
				$this->num_rows = mysql_num_rows($result);
				for ($i = 0 ; $i < $this->num_rows ; $i++){
					$array_result[$i] = mysql_fetch_assoc($result);
				}
				$this->dbfree_result($result);
			}
			else 
				$array_result = false;
			return $array_result;
		}
		/**
		 * 删除用方法
		 *
		 * @param string $sqls
		 */
		public function delete($sqls){
			$query_id=$this->query($sqls);
			$this->affected_rows = mysql_affected_rows($this->db_linker);
			$this->dbfree_result($query_id);
		}
		/**
		 * 插入用方法
		 *
		 * @param string $sql
		 */
		public function insert($sql){
			$query_id = $this->query($sql);
			$this->insert_id = mysql_insert_id($this->db_linker);
			$this->affected_rows = mysql_affected_rows($this->db_linker);
			$this->dbfree_result($query_id);
			return $query_id;
		}
		/**
		 * 更新用方法
		 *
		 * @param unknown_type $sql
		 */
		public function update($sql){
			$query_id = $this->query($sql);
			$this->insert_id = mysql_insert_id($this->db_linker);
			$this->affected_rows = mysql_affected_rows($this->db_linker);
			$this->dbfree_result($query_id);
		}
		/**
		 * 获取影响行数
		 *
		 * @return unknown
		 */
		public function get_affected_rows(){
			return $this->affected_rows;
		}
		/**
		 * 获取某个查询字段的总行数
		 *
		 * @param unknown_type $table
		 * @param unknown_type $index
		 * @param unknown_type $where
		 * @return unknown
		 */
		public function get_recodes_count($table,$index='id',$where=""){
			$sql = "SELECT COUNT(*) AS num FROM ".$table." where ".$where;
			$result = mysql_query($sql,$this->db_linker);
			if (!$result) {
				$this->dbhalt('wrong sql sentence: <br>' . $sql,false);
			}
			$num = @mysql_result($result,0,'num');
			return $num;
		}
		/**
		 * 返回结果集的行数
		 *
		 * @param unknown_type $result
		 * @return unknown
		 */
		public function get_num_of_result($result){
			return @mysql_numrows($result);
		}
		/**
		 * 关闭数据库
		 *
		 */
		function dbclose(){
			mysql_close();
		}
		
		public function __toString(){
			return (var_export($this,true));
		}
		
		
	}
	
	class photo_function extends photo {
		private $photo_name;
		private $tmp_name;
		private $photo_path;
		private $photo_type;
		private $photo_exif = '';
		private $real_path;
		private $pic_size;
		private $pic_id;
		private $sort_id,$job_id,$album_id,$cache_id;
		private $pic_tb_x = 75;
		private $pic_tb_y = 75;
		private $font_file;
		private $is_jpeg = false;
		private $is_png = false;
		
		
		/**
		 * 出错处理
		 *
		 * @param string $err_msg
		 * @param integer $return_value
		 * @return integer
		 */
		private function pic_error($err_msg,$return_value){
			if ($error_msg != '') {
				$mes = $error_msg;
			}
			else 
				$mes = 'Unknown error<br>';
			echo $mes;
			
			
			
			if (!is_numeric($return_value)) {
				return false;
			}
			else 
				return $return_value;
		}
		
		function __construct($pic_tb_x,$pic_tb_y,$photo_path){
			$this->pic_tb_x = $pic_tb_x;
			$this->pic_tb_y = $pic_tb_y;
			$this->photo_type = $photo_type;
			
			
			$this->photo_name = $photo_name;
			if (!is_file($photo_path)) {
				$this->pic_error('None of this file',-2);
			}
			$this->photo_path = $photo_path;
			$this->real_path = $photo_path;
			if (!is_file($font_file)) {
				$this->font_file = $font_file;
			}
		}
		
		public function resize_and_cut_pic($file_path,$use_jpeg = false,$use_middle = false){
			if (!$use_jpeg) {
				$img_src = imagecreatefrompng($file_path);
			}
			else 
				$img_src = imagecreatefromjpeg($file_path);
			$imgx = imagesx($img_src);
			$imgy = imagesy($img_src);
			//如果图象超过大小将自动调整
			$photo_tb_x = $this->pic_tb_x;
			$photo_tb_y = $this->pic_tb_y;
			
			if ($imgy > $this->pic_tb_y || $imgx > $this->pic_tb_x) {
				if ($imgy / ($this->pic_tb_y) < $imgx / ($this->pic_tb_x)) {
					$scale = ($this->pic_tb_y) / $imgy;
					$photo_tb_x = $imgx * $scale;
					$photo_tb_y = $this->pic_tb_y;
					$width_scale= $photo_tb_x - $this->pic_tb_x;
					$src_width_scale = $width_scale / $scale;
				}
				else{
					$scale = ($this->pic_tb_x) / $imgx;
					$photo_tb_y = $imgy * $scale;
					$photo_tb_x = $this->pic_tb_x;
					$height_scale = $photo_tb_y - $this->pic_tb_y;
					$src_height_scale = $height_scale / $scale;
				}
			}
			
			if ($use_middle) {
				if ($height_scale) {
					$tb_img = imagecreatetruecolor($photo_tb_x,$photo_tb_y - $height_scale);
					imagecopyresampled($tb_img,$img_src,0,0,0,$src_height_scale / 2,$photo_tb_x,$photo_tb_y,$imgx,$imgy);
				}
				else if ($width_scale){
					$tb_img = imagecreatetruecolor($photo_tb_x-$width_scale,$photo_tb_y);
					imagecopyresampled($tb_img,$img_src,0,0,0,0,$photo_tb_x,$photo_tb_y,$imgx,$imgy);
				}
				else {
					$tb_img = imagecreatetruecolor($photo_tb_x,$photo_tb_y);
					imagecopyresampled($tb_img,$img_src,0,0,0,0,$photo_tb_x,$photo_tb_y,$imgx,$imgy);
				}
			}
			else {
				if ($height_scale) {
					
					$tb_img = imagecreatetruecolor($photo_tb_x,$photo_tb_y - $height_scale);
				}
				else if ($width_scale){
					
					$tb_img = imagecreatetruecolor($photo_tb_x-$width_scale,$photo_tb_y);
				}
				//如果图片高宽比不需要调整
				else 
					$tb_img = imagecreatetruecolor($photo_tb_x,$photo_tb_y);
				imagecopyresampled($tb_img,$img_src,0,0,0,0,$photo_tb_x,$photo_tb_y,$imgx,$imgy);
			}
			
			$file_dir = dirname($file_path);
			$last_char = substr($file_dir,(strlen($file_dir) - 1));
			if ($last_char != '/' || $last_char != "\\") {
				$file_dir .= '/';
			}
			$filename = basename($file_path);
			if (strstr($filename,'.jpeg')) {
				$filename = substr($filename,0,strlen($filename) - strlen('.jpeg'));
			}else 
				$filename = substr($filename,0,strlen($filename) - strlen('.jpg'));
			
			$tmp_file = $file_dir . $filename . 'thb.jpg';
			$result = imagejpeg($tb_img,$tmp_file);
			imagedestroy($img_src);
			imagedestroy($tb_img);
			if ($result != 1) {
				$this->destroy_file($tmp_file);
				return false;
			}
			return $tmp_file;
			//$thumb_size = filesize($tmp_file);
			//$thumb_string = addslashes(fread(fopen($tmp_file,'r'),$thumb_size));
			//$this->destroy_file($tmp_file);
			//return $thumb_string;
		}
		
		
	}
	
	class pic_deleter{
		private $DB;
		private $uid;
		private $jid;
		private $pid;
		private $cid;
		private $tag_name;
		private $has_error;
		
		
		/**
		 * 构造函数,初始化DB类
		 *
		 * @param object $DB
		 */
		public function __construct($DB){
			$this->DB = $DB;
		}
		/**
		 * 获取错误代码
		 *
		 * @return string
		 */
		public function get_error(){
			return $this->has_error;
		}
		public function get_pid(){
			return $this->pid;
		}
		public function get_uid(){
			return $this->uid;
		}
		public function get_jid(){
			return $this->jid;
		}
		public function get_cid(){
			return $this->cid;
		}
		public function get_tagname(){
			return $this->tag_name;
		}
		/**
		 * 删除某个图片用
		 * $pid代表图片ID
		 * $uid代表这个图片所属用户ID,
		 * 如果图片ID和用户ID不符合,将返回-3
		 * 如果图片ID不是数字,将返回-1
		 * 如果用户ID不是数字,将返回-2
		 *
		 * @param int $pid
		 * @param int $uid
		 * @return int/boolen
		 */
		public function pic_del($pid,$uid,$width_job_del = false){
			$DB = $this->DB;
			if (!is_numeric($pid)) {
				return -1;
			}
			if (!is_numeric($uid)) {
				return -2;
			}
			//获取该用户以及该PID下的该图片
			$pic_del = $DB->build_and_exec_query(array('select' => '*','from' => 'photothumbs','where'=>'photothumbs_id=' . $pid . ' and album_id=' . $uid));
			$num_row = $DB->get_num_rows();
			if ($num_row == 0) {
				return -3;
			}
			$this->pid = $pid;
			$this->uid = $uid;
			//获取该图片所在任务ID
			$job_id = $pic_del['job_id'];
			//获取该图片的缓存文件并且删除
			$cache_id = $pic_del['cache_id'];
			$cache_path = $DB->build_and_exec_query(array('select' => '*','from'=>'hash_cache','where'=>'cache_id=' . $cache_id . ' and uid=' . $uid));
			$num_row = $DB->get_num_rows();
			if ($num_row > 0) {
				$cache_path = $cache_path['cache_folder'];
				if (is_file($cache_path)) {
					$del_result = @unlink($cache_path);
					//删除缩略图
					$tmp_str = str_replace('.jpg','thb.jpg',strtolower($cache_path));
					$tmp_str = str_replace('.jpeg','thb.jpeg',strtolower($tmp_str));
					if (file_exists($tmp_str)) {
						$del_result = @unlink($tmp_str);
					}
					//错误报告,这里暂时留着
					if (!$del_result) {
						$this->has_error = 'file';
					}
				}
				//删除缓存
				$DB->simple_delete('hash_cache','cache_id=' . $cache_id . ' and uid=' . $uid);
				$DB->exec_query();
			}
			//删除该图片在缩略图以及图片表里面的数据
			$DB->build_and_exec_query(array('select' => '*','from' => 'photos','where'=>'photo_id=' . $pid));
			//如果数据库里面存在该条项目,就删除,预防用户上传时的不不同步更新引发的问题
			if ($DB->get_num_rows()) {
				$DB->simple_delete('photos','photo_id=' . $pid);
				$DB->exec_query();
			}
			//删除图片缓存列表里面的内容
			$DB->simple_delete('photothumbs','photothumbs_id=' . $pid . ' and album_id=' . $uid);
			$DB->exec_query();
			//删除tag列表里面对应的内容
			$DB->simple_delete('tags_setting','photo_id=' . $pid . ' and uid=' . $uid);
			$DB->exec_query();
			if ($width_job_del) {
				//检测该任务里面的图片是否已经被删除完毕,如果已经删除完毕,删除该任务
				$pic_num = $DB->build_and_exec_query(array('select' => 'count(*) as count','from' => 'photothumbs','where'=>'job_id=' . $job_id . ' and album_id=' . $uid));
				if ($pic_num['count'] == 0) {
					$DB->simple_delete('job','job_id=' . $job_id);
					$DB->exec_query();
					//删除该任务的标签
					$DB->simple_delete('tags_setting','jid=' . $job_id . ' and uid=' . $uid);
					$DB->exec_query();
				}
			}
			
			return true;
		}
		/**
		 * 删除某个任务下所有图片以及任务本身
		 * $jid 代表任务ID
		 * $uid 代表用户ID
		 * 返回值为1,-1,-2
		 * 1代表正常
		 * -1代表任务ID不合法
		 * -2代表用户ID不合法
		 * 错误可以查询类里面的$has_error
		 *
		 * @param int $jid
		 * @param int $uid
		 * @return int
		 */
		public function job_del($jid,$uid){
			$DB = $this->DB;
			if (!is_numeric($jid)) {
				return -1;
			}
			if (!is_numeric($uid)) {
				return -2;
			}
			$this->jid = $jid;
			$this->uid = $uid;
			//获取该用户以及该JID下面的所有图片的ID;
			$DB->build_query(array('select'=>'photothumbs_id as pid','from'=>'photothumbs','where'=>'job_id=' . $jid . ' and album_id=' . $uid));
			$qid = $DB->exec_query();
			while ($row = $DB->fetch_row($qid)) {
				$pid = $row['pid'];
				if (!is_numeric($pid)) {
					continue;
				}
				//删除该任务下的单个图片
				$pic_del_result = $this->pic_del($pid,$uid);
				if ($pic_del_result <= 0) {
					$this->has_error ='job';
				}
			}
			//删除该任务的TAG以及该任务本身
			$DB->simple_delete('job','job_id=' . $jid);
			$DB->exec_query();
			//删除该任务的标签
			$DB->simple_delete('tags_setting','jid=' . $jid . ' and uid=' . $uid);
			$DB->exec_query();
			return true;
		}
		/**
		 * 删除某个任务下所有图片以及任务本身
		 * $tag_name 代表任务标签名称
		 * $uid 代表用户ID
		 * 返回值为1,-1,-2
		 * 1代表正常
		 * -1代表标签名称不合法
		 * -2代表用户ID不合法
		 * 错误可以查询类里面的$has_error
		 *
		 * @param string $tag_name
		 * @param int $uid
		 * @return int
		 */
		public function tag_del($tag_name,$uid){
			$DB = $this->DB;
			if ($tag_name == '') {
				return -1;
			}
			if (!is_numeric($uid)) {
				return -2;
			}
			$this->tag_name = $tag_name;
			$this->uid = $uid;
			//获取该标签下图片ID
			$DB->build_query(array('select'=>'photo_id as pid','from'=>'tags_setting','where'=>'tag_name=\'' . $tag_name . '\' and uid=' . $uid));
			$qid = $DB->exec_query();
			while ($row = $DB->fetch_row($qid)) {
				$pid = $row['pid'];
				if (!is_numeric($pid)) {
					continue;
				}
				//删除该任务下的单个图片(注意,这里关联删除了没有图片的相册的TAG以及该相册)
				$pic_del_result = $this->pic_del($pid,$uid,true);
				if ($pic_del_result <= 0) {
					$this->has_error ='tag';
				}
			}
			//删除该TAG
			$DB->simple_delete('tags_setting','tag_name=\'' . $tag_name . '\' and uid=' . $uid);
			$DB->exec_query();
			return true;
		}
		/**
		 * 删除某个分类下所有图片以及分类本身
		 * $cid 代表分类ID
		 * $uid 代表用户ID
		 * 返回值为1,-1,-2
		 * 1代表正常
		 * -1代表标签名称不合法
		 * -2代表用户ID不合法
		 * 错误可以查询类里面的$has_error
		 *
		 * @param int $cid
		 * @param int $uid
		 * @return int
		 */
		public function cat_del($cid,$uid){
			$DB = $this->DB;
			if (!is_numeric($cid)) {
				return -1;
			}
			if (!is_numeric($uid)) {
				return -2;
			}
			$this->cid = $cid;
			$this->uid = $uid;
			//获取该标签下图片ID
			$DB->build_query(array('select'=>'photothumbs_id as pid','from'=>'photothumbs','where'=>'sort_id=' . $cid . ' and album_id=' . $uid));
			$qid = $DB->exec_query();
			while ($row = $DB->fetch_row($qid)) {
				$pid = $row['pid'];
				if (!is_numeric($pid)) {
					continue;
				}
				//删除该分类下的单个图片(注意,这里关联删除了没有图片的相册的TAG以及该相册)
				$pic_del_result = $this->pic_del($pid,$uid,true);
				if ($pic_del_result <= 0) {
					$this->has_error ='cat';
				}
			}
			//分类是不用删除的
			return true;
		}
		/**
		 * 删除用户以及其图片
		 *
		 * @param $uid
		 * @return 
		 */
		public function user_del($uid,$width_job_del = false){
			$DB = $this->DB;
			if (!is_numeric($uid)) {
				return -2;
			}
			$this->uid = $uid;
			$username = $DB->build_and_exec_query(array(
				'select' => 'name',
				'from' => 'member_info',
				'where' => 'id=' . $uid,
			));
			$username = $username['name'];
			$DB->build_query(array('select'=>'photothumbs_id as pid','from'=>'photothumbs','where'=>'album_id=' . $uid));
			$qid = $DB->exec_query();
			while ($row = $DB->fetch_row($qid)) {
				$pid = $row['pid'];
				if (!is_numeric($pid)) {
					continue;
				}
				//删除该用户的单个图片
				$pic_del_result = $this->pic_del($pid,$uid,$width_job_del);
				if ($pic_del_result <= 0) {
					$this->has_error ='uid';
				}
			}
			//删除该用户的缓存文件夹
			$user_cache_dir = UPLOAD_DIR . $username;
			if (is_dir($user_cache_dir)) {
				@deldir($user_cache_dir);
			}
			//删除该用户
			$DB->simple_delete('member_info','id=' . $uid);
			$DB->exec_query();
			return true;
		}
		
	}
	
	
	
	
	
	
	
	
?>